//package cn.com.zetatech.loader.service.impl;
//
//import cn.com.zetatech.loader.config.FileMoverConfig;
//import cn.com.zetatech.loader.entity.*;
//import cn.com.zetatech.loader.enums.AccessTypeEnum;
//import cn.com.zetatech.loader.mapper.SourceFileMapper;
//import cn.com.zetatech.loader.mapper.TransferMsgLogMapper;
//import cn.com.zetatech.loader.service.FileTransferService;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.util.IdUtil;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.kafka.common.protocol.types.Field;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.io.IOException;
//import java.net.InetAddress;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.nio.file.StandardCopyOption;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.Optional;
//import java.util.concurrent.*;
//
///**
// * @author jian.chen@zetatech.com.cn
// * @Description TODO
// * @Date 2024/7/10 10:10
// */
//@Slf4j
//@Service
//public class FileTransferServiceImpl implements FileTransferService {
//
//    private final FileMoverConfig fileMoverConfig;
//
//    @Autowired
//    private SourceFileMapper sourceFileMapper;
//
//    @Autowired
//    private TransferMsgLogMapper transferMsgLogMapper;
//
//    public FileTransferServiceImpl(FileMoverConfig fileMoverConfig) {
//        this.fileMoverConfig = fileMoverConfig;
//    }
//
//    private static final int MAX_RETRY_COUNT = 3;
//
//    @Override
//    public int moveFiles(ResolverHuangshanMessage resolverMessage) {
//        LocalDateTime currentDate = LocalDateTime.now();
//        String year = currentDate.format(DateTimeFormatter.ofPattern("yyyy"));
//        String month = currentDate.format(DateTimeFormatter.ofPattern("MM"));
//        String day = currentDate.format(DateTimeFormatter.ofPattern("dd"));
//        String hour = currentDate.format(DateTimeFormatter.ofPattern("HH"));
//
//        Path datedDestDir = Paths.get(fileMoverConfig.getDestDir(), year, month, day, hour);
//
//        List<String> sourceFilePathList = sourceFileMapper.sourceFilePathList(resolverMessage);
//        int moves = 0;
//        ThreadPoolExecutor logExecutorService = new ThreadPoolExecutor(
//                5,
//                5,
//                0L,
//                TimeUnit.MILLISECONDS,
//                new ArrayBlockingQueue<>(100)
//        );
//
//        for (String dirPathFiled : sourceFilePathList) {
//            int lastSlashIndex = dirPathFiled.lastIndexOf('/');
//            String sourceFilePath = dirPathFiled.substring(0, lastSlashIndex);
//            String sourceFileName = dirPathFiled.substring(lastSlashIndex + 1);
//
//            boolean exists = Files.exists(Paths.get(sourceFilePath, sourceFileName));
//            if (exists) {
////                int retryCount = Optional.ofNullable(resolverMessage.getRetryCount()).orElse(2);
//                int retryCount = 2;
//                boolean moveSuccessful = false;
//
//                while (!moveSuccessful && retryCount < MAX_RETRY_COUNT) {
//                    try {
//                        log.info("文件移动开始：{}", sourceFileName);
//                        String fileFullPath = Paths.get(sourceFilePath, sourceFileName).toString();
//                        long fileSize1 = Files.size(Paths.get(fileFullPath));
//
//                        if (fileSize1 == 0) {
//                            log.info("文件大小为0，忽略本次文件：{}", sourceFileName);
//                            break;
//                        }
//
//                        Thread.sleep(100L);
//                        long fileSize2 = Files.size(Paths.get(fileFullPath));
//
//                        if (fileSize2 != fileSize1) {
//                            log.info("文件大小变化中，忽略本次文件：{}", sourceFileName);
//                            break;
//                        }
//
//                        Files.createDirectories(Paths.get(datedDestDir.toString()));
//                        String newFileName = sourceFileName;
//
//                        Files.move(Paths.get(sourceFilePath, sourceFileName),
//                                Paths.get(datedDestDir.toString(), newFileName),
//                                StandardCopyOption.REPLACE_EXISTING);
//
//                        log.info("NAS文件：{} 移动到: {} 成功",
//                                Paths.get(sourceFilePath, sourceFileName),
//                                Paths.get(datedDestDir.toString(), newFileName)
//                        );
//
//                        moves += 1;
//
//                        int finalRetryCount = retryCount;
//                        logExecutorService.submit(() -> {
//                            try {
//                                TransferMsgLog transferMsgLog = new TransferMsgLog();
//                                transferMsgLog.setId(IdUtil.simpleUUID());
//                                transferMsgLog.setDay(LocalDateTime.now().getDayOfMonth());
//                                transferMsgLog.setMonth(LocalDateTime.now().getMonthValue());
//                                transferMsgLog.setYear(LocalDateTime.now().getYear());
//                                transferMsgLog.setType("NAS"); // Assuming NAS here
//                                MoveRecord record = new MoveRecord();
//                                record.setState("SUCCESS");
//                                record.setRetryCount(finalRetryCount);
//                                record.setRunDuration(System.currentTimeMillis());
//                                record.setPosition(InetAddress.getLocalHost().getHostAddress());
//                                ObjectMapper objectMapper = new ObjectMapper();
//                                transferMsgLog.setMessage(objectMapper.writeValueAsString(record));
//                                transferMsgLog.setStatus(1);
//                                transferMsgLog.setCreateTime(DateUtil.now());
//                                transferMsgLogMapper.insert(transferMsgLog);
//                            } catch (Exception e) {
//                                log.error("日志记录失败: {}", e.getMessage(), e);
//                            }
//                        });
//
//                        moveSuccessful = true;
//                    } catch (IOException e) {
//                        log.error("文件移动失败:{}", e.getMessage(), e);
//                        retryCount++;
//                    } catch (InterruptedException e) {
//                        log.error("文件移动异常:{}", e.getMessage(), e);
//                        retryCount++;
//                        Thread.currentThread().interrupt();
//                    }
//                }
//
//                if (!moveSuccessful) {
//                    log.error("文件移动失败，达到最大重试次数，文件名：{}", sourceFileName);
//                    int finalRetryCount1 = retryCount;
//                    logExecutorService.submit(() -> {
//                        try {
//                            TransferMsgLog transferMsgLog = new TransferMsgLog();
//                            transferMsgLog.setId(IdUtil.simpleUUID());
//                            transferMsgLog.setDay(LocalDateTime.now().getDayOfMonth());
//                            transferMsgLog.setMonth(LocalDateTime.now().getMonthValue());
//                            transferMsgLog.setYear(LocalDateTime.now().getYear());
//                            transferMsgLog.setType("NAS"); // Assuming NAS here
//                            MoveRecord record = new MoveRecord();
//                            record.setState("FAILED");
//                            record.setRetryCount(finalRetryCount1);
//                            record.setRunDuration(System.currentTimeMillis());
//                            record.setPosition(InetAddress.getLocalHost().getHostAddress());
//                            ObjectMapper objectMapper = new ObjectMapper();
//                            transferMsgLog.setMessage(objectMapper.writeValueAsString(record));
//                            transferMsgLog.setStatus(0);
//                            transferMsgLog.setCreateTime(DateUtil.now());
//                            transferMsgLogMapper.insert(transferMsgLog);
//                        } catch (Exception e) {
//                            log.error("日志记录失败: {}", e.getMessage(), e);
//                        }
//                    });
//                }
//            }
//        }
//
//        logExecutorService.shutdown();
//        try {
//            logExecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
//        } catch (InterruptedException e) {
//            log.error("等待日志记录任务完成时出现异常: {}", e.getMessage(), e);
//            Thread.currentThread().interrupt();
//        }
//
//        return moves;
//    }
//
//
//    @Override
//    public List<Map<String, Object>> loaderEfficiencyTrendChart(ChartParam chartParam) {
//        return transferMsgLogMapper.loaderEfficiencyTrendChart(chartParam);
//    }
//
//    @Override
//    public List<Map<String, Object>> pollingEfficiencyTrendChart(ChartParam chartParam) {
//        return transferMsgLogMapper.pollingEfficiencyTrendChart(chartParam);
//    }
//}
